<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<link href="../../cssmui/mui.min.css" rel="stylesheet" />

		<link href="../../css/app.css" rel="stylesheet" />
		<link href="../../css/mylist.css" rel="stylesheet" />
		<script src="../../mui/mui.min.js"></script>
		<script src="../../js/vue.min.js"></script>
		<script src="../../js/common.js"></script>
		<script src="../../js/app.js"></script>

		<script src="../../js/jsondb.js"></script>
		<script src="../../js/zdyfile.js"></script>
		<script src="../../js/mysimg.js"></script>
		<script src="../../js/map/ioservices.js"></script>
		<script src="../../js/map/dictservice.js"></script>

		<style type="text/css">
			.mui-slider-group {
				height: 190px
			}
			
			.mui-content {
				margin-bottom: 70px;
			}
			
			.selectprice {
				color: #E1673E;
				font-size: 12pt;
			}
			
			.mui-card {
				position: relative;
				/*设置圆角*/
				-webkit-border-radius: 5px;
				-moz-border-radius: 5px;
				border-radius: 5px;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">采购-细项</h1>
			<button id="scanBtn" onclick="clicked('../../plus/barcode_scan.html',true,true)" class="mui-pull-right myheadBtn" type="button" onclick="return false; ">扫描</button>
			<button id="selBtn" class="mui-pull-right myheadBtn" type="button" onclick="return false; ">选择</button>
		</header>

		<div class="mui-content ">
			<div class="vuediv">

				<div class="mui-card mui-card-content-inner mui-row " style="height:80px">
					<div class="subscript"> </div>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 识别码：</span>
					<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{gid||'请选择商品'}} </span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 名称：</span>
					<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{gname||'请选择商品'}}</span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 分类：</span>
					<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{getGclass(gclass)||'未分类'}}</span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 规格：</span>
					<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{spec||'无'}}</span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 单重：</span>
					<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{gweight||'无'}}kg </span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 体积：</span>
					<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{cbcm||'无'}}立方</span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 上次进价￥</span>
					<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{price1||'无'}} </span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 上次售价￥</span>
					<span class="mui-col-sm-3 mui-col-xs-3 text_content selectprice ">{{price2||'无'}} </span>

					<span class="mui-col-sm-3 mui-col-xs-3 "> 保质期：</span>
					<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{quality||'无'}} </span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 库存：</span>
					<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{库存||'0'}} </span>
					<span class="mui-col-sm-3 mui-col-xs-3 "> 产地：</span>
					<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{gaddr||'无'}}</span>
					<span class="mui-col-sm-3 mui-col-xs-3 ">备注：</span>
					<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{gnote||'无'}} </span>
					<span class="mui-col-sm-6 mui-col-xs-6  ">{{titleconfig[1]}}￥：</span>
					<span class="mui-col-sm-6 mui-col-xs-6 text_content selectprice">{{lastprice||'无'}} </span>

					<div class=" mui-row" v-for="r in levelprices">
						<span class="mui-col-sm-7 mui-col-xs-7 ">{{getUlevel(r.level)}}单价￥：</span>
						<span class="mui-col-sm-5 mui-col-xs-5 text_content mui-h4 selectprice">{{r.price||'无'}} </span>
					</div>
				</div>

				<form class="mui-input-group ">
					<div style="background-color:beige; ">
						<div class="mui-input-row ">
							<label id='pricelabel'>{{gnote||'无'}}</label>
							<input id="price" type="number" v-number-only v-model="price" placeholder="请输入有效数值" value="0.0">
						</div>
						<div class="mui-input-row ">
							<label>数量：</label>
							<div class="mui-numbox" style="width: 180px;height: 35px;">
								<button class="mui-btn mui-numbox-btn-minus" type="button">-</button>
								<input id="num" class="mui-input-numbox " v-number-only v-model="num" type="number" placeholder="请输入有效数值" value="0" />
								<button class="mui-btn mui-numbox-btn-plus" type="button">+</button>
							</div>
						</div>
						<div class="mui-input-row pamountdiv1">
							<label>金额：</label>
							<input type="number" v-number-only readonly v-model="damount" placeholder="请输入有效数值" value="0.0">
						</div>

					</div>
				</form>
			</div>

			<ul class="mui-table-view ">

				<li class="mui-table-view-cell ">
					<a href="#">图片</a>
					<div class="mui-row">
						<div id="slider " class=" mui-slider ">
							<div id="divphotos" class="mui-slider-group ">
								<div v-for="(item,index) in imgs" class="mui-slider-item img-btn">

									<img class="sliderimg" onload="imgLoaded(this)" v-on:click="onclick(event)" :src="item.src">
								</div>
							</div>
						</div>
					</div>
				</li>
			</ul>
		</div>

		<nav class="mui-bar mui-bar-tab">
			<a id="btncancel" class="mui-tab-item">
				<span class="mui-tab-label">返回</span>
			</a>
			<a id='btnsave' class="mui-tab-item">
				<span class="mui-tab-label">确认</span>
			</a>
		</nav>
		<script type="text/javascript">
			var _PORS = 'b1';
			//----定义
			var vw_prod = null;
			var targetTab = ['goods_list.html'];

			var _tb_io1 = new XCDBHelp('tb_io1');
			var _tb_price_mon = new XCDBHelp('tb_price_mon');
			var _tb_goods = new XCDBHelp('tb_goods');
			var _tb_contacts = new XCDBHelp('tb_contacts');
			//	console.log(JSON.stringify(_tb_types.getObjByID('gclass')));
			var DICT_gclass = null;
			var DICT_ulevel = null; // _tb_types.getObjByID('gclass')._data;
			var _isreadonly = false; //是否只读
			var _vu = null; //当前vue模版
			var _mould = { //默认模版
				//tb_io1
				did: null,
				pid: '',
				cid: '',
				pors: '',
				gid: '',
				price: 0,
				num: 0,
				damount: 0,
				weight: 0,
				size: 0,
				remark: '',
				status: '1',
				//tb_goods
				gclass: '',
				gname: '',
				spec: '',
				gweight: 0,
				cbcm: 0,
				gaddr: '',
				price1: 0,
				price2: 0,
				lastprice: 0,
				levelprices: [],
				gnote: '',
				gimg: '',
				quality: 0,
				//report
				库存: '',
				titleconfig: []
			}
			var _curmd = null; //当前的模型
			var _curgood = null; //当前商品

			//----------------初始化-------------
			mui.init();
			mui.ready(function() {

				//				if(ISDEVELOP=='1'){	//开发模式下启用
				//					createMd();
				//				}
				//选择商品以后会改变触发改变事件
				window.addEventListener('bechanged', function(e) {　 //获取参数值		
					//alert(e.detail.reload)
					if(e.detail.reload == 'good') { //商品发生改变
						//	log(e.detail.data, 'purchase_item.html157')						
						var id = e.detail.data;
						//alert(id);
						getGood(id);
						getPrice(id);
						//_curmd.price = _curgood.price1;//用最近的进价做参考
					}
				});
				//-------------监听事件不受vue框架影响必须防止vue mounted 之后----------
				//选择价格
				mui('.mui-content').on('tap', '.selectprice', function(e) {
					var v = this.innerText.trim();
					//console.log(v);
					if(v == '无') return;
					_curmd.price = Number(v);
					//然后监听 bechanged事件 
				});

				//------------按钮事件--------------	
				//选择商品事件
				mui(document.body).on('tap', '#selBtn', function(e) {
					open(targetTab[0], {
						target: 'sel'
					})
					//然后监听 bechanged事件 
				});
				//底部按钮

				mui("nav").on("tap", "#btnsave", function() {
					save();
				});
				mui("nav").on("tap", "#btncancel", function() {
					_reload = 0;
					mui.back();
				});
				mui("nav").on("tap", ".btndel", function() {
					del();
				});
				//-------样式事件----------
				//卡片缩小事件
				mui(".mui-content").on('tap', '.subscript', function(e) {
					t = this.parentNode;
					if(t.style.height == "")
						t.style.height = "80px"
					else
						t.style.height = ""
				});

			});

			function loaddict() {
				//console.log(JSON.stringify(_tb_types.getObjByID('gclass')));
				DICT_gclass = getDictGclass()
				DICT_ulevel = getDictUlevel();
			}
			//plus初始化
			function afterPlusReady() {
				//载入数据		

				_si = new SliderImage("divphotos");

				loaddict();
				var self = _self;
				setPors(self.pors)

				if(self.selectedid) { //编辑如果当前id有值	
					if(self.pstatus < 2) //如果主单据 未保存可以修改,
					{
						addMuibarDelbtn();
						_isreadonly = false;
						G('num').setAttribute("readOnly", "false");
					} else {
						_isreadonly = true;
						G('scanBtn').style.display = "none";
						G('selBtn').style.display = "none";
						G('num').setAttribute("readOnly", "true");
						G('btnsave').style.display = "none";
					}

					//console.log('goodsinfo242:'+_curmd.pid)
					loadDataById(self.selectedid);
				} else if(self.pid) { //新增					
					createMd();
					_curmd.pid = self.pid;
					_curmd.cid = self.cid;
					//_curmd.pors = self.pors;
				}

			}

			function setPors(p) {
				//console.log(p);
				_PORS = p;
				switch(_PORS) {
					case 'b1':
						_titleconfig = ['采购', '进价']
						break;
					case 's1':
						_titleconfig = ['销售', '售价']
						break;
					case 'rb1':
						_titleconfig = ['采购退货', '价格']
						break;
					case 'rs1':
						_titleconfig = ['销售退货', '价格']
						break;
				}

				mui('header .mui-title')[0].innerHTML = _titleconfig[0] + "商品";
				mui('#pricelabel')[0].innerHTML = _titleconfig[1];

			}

			function addMuibarDelbtn() {
				var html = '<a class="mui-tab-item btndel"><span class="mui-tab-label">删除</span></a>'
				document.querySelector('.mui-bar-tab').innerHTML += html;
			
			}

			//------------模型与算法 ---------------
			//数量改变计算总金额,总重量,总体积			
			//价格
			function fireCount() {
				_curmd.damount = round2(_curmd.price * _curmd.num, 2);
				_curmd.size = round2(_curmd.cbcm * _curmd.num, 2);
				_curmd.weight = round2(_curmd.gweight * _curmd.num, 2);
			}
			//写入模板
			function bindVU() {
				_curmd.titleconfig = _titleconfig;

				_vu = new Vue({
					//el: '#prod_div',
					el: '.vuediv',
					data: _curmd,
					methods: {
						getGclass: function(id) {
							return getDictText(DICT_gclass, id);
						},
						getUlevel: function(id) {
							return getDictText(DICT_ulevel, id);
						}
						//						round2:function(a,b){
						//							return round2(a,b)
						//						}
					},

					watch: {
						num: function(val, old) {
							//G('num').value = _curmd.num;
							//console.log(val+' '+old)
							//this.num						
							fireCount()
						},
						price: function(val, old) {
							//console.log("ccc"+val+', '+old);
							//							if (old)
							//								this.price= val.replace(/[^\d\.]/g, old);
							fireCount()
						}
					},
					directives: {
						numberOnly: {
							bind: function(el) {
								el.handler = function() {
									el.value = el.value.replace(/[^\d\.]/g, '');
									//el.value =obj.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
								}
								el.addEventListener('input', el.handler)
							},
							unbind: function(el) {
								el.removeEventListener('input', el.handler)
							}
						}
					}
				});
				//mui(".mui-input-group").on('input', '.inputnum', function() {
				//				
				//						this.value = this.value.replace(/[^\d\.]/g, '');
				//					});
				//坑: vue 会洗掉原来的脚本 所以必须重写
				//-----------表单事件-------------
				//数量改变
				mui(".mui-numbox").on('tap', '.mui-numbox-btn-minus', function(e) {
					if(_curmd.num > 0 && !_isreadonly) {
						var n = round2(_curmd.num, 2) - 1;
						_curmd.num = n < 0 ? 0 : n;
					}

					document.activeElement.blur();
				});

				mui(".mui-numbox").on('tap', '.mui-numbox-btn-plus', function(e) {
					if(!_isreadonly)
						_curmd.num = round2(_curmd.num, 2) + 1
					document.activeElement.blur();
				});

				fireCount();
			}
			//----------------orm函数-------------

			//创建tb_io1表的新记录
			function createMd() {
				_curmd = clone(_mould)
				bindVU()
			}
			//通过id载入数据
			function loadDataById(selid) {
				var rc = _tb_io1.getObjByID(selid)
				//console.log(JSON.stringify(rc))
				if(rc) {
					readData(rc)
				}
				bindVU()
			}
			//读取数据到模型
			function readData(data) {
				_curmd = clone(_mould);
				_curmd.did = data._idkey;
				_curmd.pid = data.pid;
				_curmd.cid = data.cid;
				_curmd.gid = data.gid;
				_curmd.price = data.price;
				_curmd.num = data.num;
				_curmd.damount = data.damount;
				_curmd.weight = data.weight;
				_curmd.size = data.size;
				_curmd.remark = data.remark;
				_curmd.status = data.status;
				getGood(data.gid);
			}

			//--------------数据写入------------------

			//写入持久层
			function save() {
				var data = {};
				if(_curmd.gid == null || _curmd.gid == '') {
					mui.alert('请选择商品')
					return;
				}
				if(_IS.isEmptyString(_curmd.pid)) {
					mui.alert('程序异常,返回上一级页面重新添加')
					return;
				}
				if(_curmd.num == 0) {
					mui.alert('请输入' + _titleconfig[0] + '数量')
					return;
				}
				//console.log(' _curmd.did'+ _curmd.did)
				data._idkey = _curmd.did;
				data.pid = _curmd.pid;
				data.cid = _curmd.cid;
				data.gid = _curmd.gid;
				data.pors = _PORS;
				data.price = round2(_curmd.price, 2); //).toFixed(2)// round2(_curmd.price,2);
				data.num = round2(_curmd.num, 2);
				data.damount = round2(_curmd.damount, 2); // round2(_curmd.damount,3);
				data.weight = round2(_curmd.weight, 2);
				data.size = round2(_curmd.size, 2);
				data.remark = _curmd.remark;
				data.status = _curmd.status;

				_tb_io1.setObj(data);
				setGood(); //把最近的进价保存
				_reload = 'itemp';
				mui.back();
			}

			function del() {
				mui.confirm('你确定要从订单中删除本明细吗？', '', ['否', '是'], function(e) {
					if(e.index == 1) {
						console.log(_curmd.did)
						_tb_io1.delObjById(_curmd.did);
						_reload = 'itemp';
						mui.back();
					}
				});
			}
			//----------------回调函数---------------			
			//扫描回调函数type: t,result: r,file: f
			function scaned(t, r, f) {
				getGood(r);
				getPrice(r);
			}

			//商品信息
			//重新选择商品
			function getGood(id) {
				_curgood = _tb_goods.getObjByID(id);
				if(_curgood == null) return;
				_curmd.gid = id;
				_curmd.gaddr = _curgood.gaddr;
				_curmd.gname = _curgood.gname;
				_curmd.gclass = _curgood.gclass;
				_curmd.spec = _curgood.spec;
				_curmd.gweight = _curgood.weight; //单位重量
				_curmd.cbcm = _curgood.cbcm; //单位体积
				_curmd.price1 = round2(_curgood.price1, 2); ////进价
				_curmd.price2 = round2(_curgood.price2, 2); //  //售价	
				_curmd.levelprices = _curgood.levelprices;
				_curmd.gnote = _curgood.gnote;
				_curmd.库存 = _IOM.getStoreNum(id);
				_curmd.gimg = _curgood.gimg;
				_curmd.quality = _curgood.quality; //保质期
				//console.log(_curgood.gimg)
				_si.loadImgs(_curgood.gimg); //???
			}

			function getPrice(gid) {
				if(_PORS == 'b1' || _PORS == 'rb1') {
					_curmd.price = getPrice3mon(_curmd.cid, gid); //用最近的进价做参考
					if(_curmd.price == 0)
						_curmd.price = _curmd.price1;
				} else if(_PORS == 's1' || _PORS == 'rs1') {
					var lvl = getClevel(_curmd.cid);
					if(lvl) {
						_curmd.price = getPriceLevel(lvl); //用最近3个月的售价/等级价/做参考
					}
					if(_curmd.price == 0) {
						_curmd.price = getPrice3mon(_curmd.cid, gid);
					}
					if(_curmd.price == 0) {
						_curmd.price = _curmd.price2;
					}
				}
			}

			function getPrice3mon(cid, gid) {
				var mon_3 = new Date().addMonths(-3).Format("yyyyMM");
				//查找最近三个月的进价
				var arr0 = _tb_price_mon.where({
					"cid": cid,
					"gid": gid,
					"monnum[": mon_3
				}).getList();
				//有该商品3个月销售记录，取最近一次价格设定售价
				if(arr0.length > 0) {
					_curmd.lastprice = arr0[0].price
					return _curmd.lastprice;
				}
				return 0;
			}

			function getClevel(cid) {
				var a0 = _tb_contacts.getObjByID(cid);
				return a0.clevel;
			}
			//如果有会员身份以会员价为准
			//如果没有会员等级以最近一次价格为准
			function getPriceLevel(lvl) {
				var arr = _curmd.levelprices;
				//console.log(JSON.stringify(arr));
				//console.log(JSON.stringify(ulevel) );
				//console.log(a0.clevel-1);
				//与交易对象匹配的售价
				for(var i = 0; i < arr.length; i++) {
					//console.log(arr[i]['level']);
					if(arr[i]['level'] == lvl)
						return arr[i]['price'];
				}
				return 0;

			}
			//销售和采购的时候保存成交价格
			function setGood(price) {
				//	console.log("setGood1:"+JSON.stringify(_curgood))
				if(_curgood) {
					if(_PORS == 'b1') {
						//最近进价				
						_curgood.price1 = _curmd.price;
						_tb_goods.setObj(_curgood)

					} else if(_PORS == 's1') {
						//最近售价			
						_curgood.price2 = _curmd.price;
						_tb_goods.setObj(_curgood)

					}
				}
				//	console.log("setGood2:"+JSON.stringify(_curgood))
			}
		</script>

	</body>

</html>